package hellfire.system.engine;

import hellfire.platform.screens.AbstractGameScreen;
import hellfire.platform.screens.ChickenScreen;
import hellfire.system.graphics.GLRenderer;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Vector;

import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.util.Log;

public class Engine implements Runnable
{
	public static Object Lock = new Object();
	public static boolean Freeze = false;
	
	private Integer ticks;
	private boolean shouldStop;
	private Vector<Task> tasks;
	private AbstractGameScreen currentGameScreen;
	
	public Engine()
	{
		ticks = 0;
		shouldStop = false;
		tasks = new Vector<Task>();
		currentGameScreen = null;
	}
	
	public void run() 
	{
		Log.d("R", "Engine Start");
		while(!shouldStop)
		{
			try { Thread.sleep(1000); continue; } catch (InterruptedException e1) {}
			if(shouldStop) break;
			if(Freeze) continue;
			synchronized(Lock)
			{
				ticks++;
				try
				{
					for(Task t : tasks)
					{
						t.run();
					}
					tasks.clear();
					if(currentGameScreen != null)
						currentGameScreen.gameFrame();
					else
					{
						if(GLRenderer.isSurfaceCreated)
							currentGameScreen = new ChickenScreen();
					}
				}
				catch(Exception e)
				{
					Engine.Freeze = true;
					StringWriter sw = new StringWriter();
					PrintWriter pw = new PrintWriter(sw);
					e.printStackTrace(pw);
					pw.flush();
					
					Main.MessageBoxStrict("Engine crash:\n" + sw.toString(), new OnClickListener() 
					{
						public void onClick(DialogInterface dialog, int which) 
						{
							terminate();
						}
					}); 
					e.printStackTrace();
				}
			}
		}
		Main.Engine = null;
		Main.EngineThread = null;
		Main.Activity.finish();
		Main.Activity=null;
	}

	public int getTicks()
	{
		return ticks;
	}
	
	public AbstractGameScreen getCurrentGameScreen()
	{
		return currentGameScreen;
	}
	
	public void setGameScreen(AbstractGameScreen gameScreen)
	{
		currentGameScreen = gameScreen;
	}
	
	public void onBack()
	{
		if(currentGameScreen != null)
			currentGameScreen.onBack();
	}
	
	public void runTask(Task t)
	{
		tasks.add(t);
	}
	
	public void terminate()
	{
		shouldStop = true;
	}
	
}
